package com.palfund.receiver;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

/**
 * priority:
 * OwnStaticReceiver 360
 * OwnDynamicReceiver 380
 * StaticReceiver 660
 * DynamicReceiver 680
 * DynamicCancelReceiver 690
 * 静态注册的Receiver,不启动app也能接收到广播
 * 动态注册的Receiver在Activity销毁时,需要取消注册否则会报错(不取消注册也接收不到广播)
 * 动态注册的Receiver注册后才能收到广播,取消注册后便不能收到广播
 * 有序广播可以被优先级别高的广播接收器终止abortBroadcast()
 * 有序广播中优先级别高的广播接收器可以中途向优先级别低的广播接收器添加信息
 */

public class MainActivity extends AppCompatActivity {

    private DynamicReceiver mDynamicReceiver;
    private DynamicCancelReceiver mDynamicCancelReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化Receiver
        mDynamicReceiver = new DynamicReceiver();
        //实例化IntentFilter
        IntentFilter intentFilter = new IntentFilter();
        //添加Action
        intentFilter.addAction("com.palfund.broadcast.receive");
        //设置优先级
        intentFilter.setPriority(680);
        //动态注册广播接收器
        registerReceiver(mDynamicReceiver, intentFilter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 1, 1, "register");
        menu.add(Menu.NONE, 2, 1, "unRegister");
        menu.add(Menu.NONE, 3, 1, "send");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                mDynamicCancelReceiver = new DynamicCancelReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("com.palfund.broadcast.receive");
                intentFilter.setPriority(690);
                registerReceiver(mDynamicCancelReceiver, intentFilter);
                break;
            case 2:
                unregisterReceiver(mDynamicCancelReceiver);
                break;
            case 3:
                Intent intent = new Intent();
                intent.setAction("com.palfund.broadcast.receive");
                intent.putExtra("info", "send");
                sendBroadcast(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mDynamicReceiver);
    }
}
